<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class PerformanceAssessment extends Model
{
	use SoftDeletes;
	protected $fillable = ['employee_id', 'reviewer_id', 'title', 'type', 'period', 'is_weight', 'status', 'overall_rating', 'begin_at', 'end_at'];
	protected $casts = [
		'begin_at'  => 'datetime:Y-m-d',
		'end_at'  => 'datetime:Y-m-d'
	];

	public static $typeMap	=	[
		0	=>	'普通岗',
		1	=>	'管理岗',
	];

	public static $periodMap	=	[
		'year'	=>	'年度',
		// 'quarter'=>	'季度',
		'month'	=>	'月度',
		// 'week'	=>	'周度',
		'day'	=>	'日度',
	];

	const STATUS_DRAFT	=	'draft';
	const STATUS_SELF	=	'self';
	const STATUS_OTHER	=	'other';
	const STATUS_COMPLETED	=	'completed';

	public static $statusMap	=	[
		self::STATUS_DRAFT	=>	'草稿',
		self::STATUS_SELF	=>	'自评中',
		self::STATUS_OTHER	=>	'Ta评中',
		self::STATUS_COMPLETED	=>	'已完成',
	];

	protected static function boot()
	{
		parent::boot();
		static::creating(function ($m) {
			if (!$m->no) {
				$m->no = static::findAvailableNo();
				if (!$m->no) return false;
			}
		});
	}

	public function employee() {
		return $this->belongsTo(Employee::class);
	}

	public function reviewer() {
		return $this->belongsTo(Employee::class);
	}
	
	public function performanceItems() {
		return $this->hasMany(PerformanceItem::class);
	}

	public function scopeWhichKeyword($q, $w)
	{
		if (! $w) return $q;
		return $q->where(self::qualifyColumn('no'), 'like', "%{$w}%")
				->orWhere(self::qualifyColumn('title'), 'like', "%{$w}%");
	}

	public function scopeWhichEmployee($q, $s, $u = 0)
	{
		if (!$s) return $q;
		if (!is_array($s)) {
			$s = [$s];
		}
		$q->whereIn(self::qualifyColumn('employee_id'), $s);
		if ($u) {
			foreach ($s as $i) {
				DB::table('search_weights')->updateOrInsert(['user_id' => $u, 'employee_id' => $i]);
			}
			DB::table('search_weights')->where('user_id', $u)->whereIn('employee_id', $s)->increment('total');
		}
	}

    public function scopeWhichType($q, $s)
    {
        if (! $s) return $q;
        if (!is_array($s)) {
            $s = [$s];
        }
        return $q->whereIn(self::qualifyColumn('type'), $s);
    }

    public function scopeWhichStatus($q, $s)
    {
        if (! $s) return $q;
        if (!is_array($s)) {
            $s = [$s];
        }
        return $q->whereIn(self::qualifyColumn('status'), $s);
    }

	public static function findAvailableNo()
	{
		$prefix = 'PA'.date('YmdHis');
		for ($i = 0; $i < 4; $i++) {
			$no = $prefix.str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT);
			if (!static::query()->whereNo($no)->exists()) return $no;
			usleep(100);
		}
		\Log::warning(sprintf('find contract no failed'));
		return false;
	}
}
